const ReportConfig = require('../models/ReportConfig');
const ReportPermission = require('../models/ReportPermission');
const ReportExport = require('../models/ReportExport');
const ReportSubscription = require('../models/ReportSubscription');
const { logger } = require('../utils/logger');
const db = require('../config/database');

class ReportController {
  // 获取报表列表
  async getReports(req, res) {
    try {
      const { category, search } = req.query;
      const userRole = req.user?.role || 'employee';
      const userId = req.user?.id;

      // 获取用户可访问的报表
      const accessibleReports = await ReportPermission.getUserAccessibleReports(userId, userRole);
      
      let reports = await ReportConfig.findAll();
      
      // 筛选用户有权限的报表
      reports = reports.filter(report => 
        accessibleReports.some(ar => ar.report_key === report.report_key)
      );

      // 按分类筛选
      if (category) {
        reports = reports.filter(report => report.category === category);
      }

      // 搜索筛选
      if (search) {
        const searchLower = search.toLowerCase();
        reports = reports.filter(report => 
          report.name.toLowerCase().includes(searchLower) ||
          report.description.toLowerCase().includes(searchLower)
        );
      }

      // 按分类分组
      const groupedReports = reports.reduce((acc, report) => {
        if (!acc[report.category]) {
          acc[report.category] = [];
        }
        acc[report.category].push(report);
        return acc;
      }, {});

      res.json({
        success: true,
        data: {
          reports: groupedReports,
          total: reports.length
        }
      });
    } catch (error) {
      logger.error('获取报表列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取报表列表失败',
        error: error.message
      });
    }
  }

  // 获取报表配置
  async getReportConfig(req, res) {
    try {
      const { reportKey } = req.params;
      const userRole = req.user?.role || 'employee';
      const userId = req.user?.id;

      // 检查权限
      const hasPermission = await ReportPermission.checkPermission(userId, userRole, reportKey);
      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '没有访问此报表的权限'
        });
      }

      const config = await ReportConfig.findByKey(reportKey);
      if (!config) {
        return res.status(404).json({
          success: false,
          message: '报表配置不存在'
        });
      }

      res.json({
        success: true,
        data: config
      });
    } catch (error) {
      logger.error('获取报表配置失败:', error);
      res.status(500).json({
        success: false,
        message: '获取报表配置失败',
        error: error.message
      });
    }
  }

  // 生成报表数据
  async generateReport(req, res) {
    try {
      const { reportKey } = req.params;
      const filters = req.body || {};
      const userRole = req.user?.role || 'employee';
      const userId = req.user?.id;

      // 检查权限
      const hasPermission = await ReportPermission.checkPermission(userId, userRole, reportKey);
      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '没有访问此报表的权限'
        });
      }

      // 获取报表配置
      const config = await ReportConfig.findByKey(reportKey);
      if (!config) {
        return res.status(404).json({
          success: false,
          message: '报表配置不存在'
        });
      }

      // 获取数据范围筛选条件
      const dataFilters = await ReportPermission.getDataScopeFilters(userId, userRole, reportKey);
      
      // 合并筛选条件
      const finalFilters = { ...filters, ...dataFilters };

      // 根据报表类型生成数据
      let reportData;
      switch (config.category) {
        case 'financial':
          reportData = await this.generateFinancialReport(reportKey, finalFilters);
          break;
        case 'sales':
          reportData = await this.generateSalesReport(reportKey, finalFilters);
          break;
        case 'product':
          reportData = await this.generateProductReport(reportKey, finalFilters);
          break;
        case 'customer':
          reportData = await this.generateCustomerReport(reportKey, finalFilters);
          break;
        default:
          throw new Error(`不支持的报表类型: ${config.category}`);
      }

      res.json({
        success: true,
        data: {
          config,
          filters: finalFilters,
          ...reportData
        }
      });
    } catch (error) {
      logger.error('生成报表数据失败:', error);
      res.status(500).json({
        success: false,
        message: '生成报表数据失败',
        error: error.message
      });
    }
  }

  // 导出报表
  async exportReport(req, res) {
    try {
      const { reportKey } = req.params;
      const { format = 'xlsx', filters = {} } = req.body;
      const userRole = req.user?.role || 'employee';
      const userId = req.user?.id;

      // 检查权限
      const hasPermission = await ReportPermission.checkPermission(userId, userRole, reportKey);
      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '没有访问此报表的权限'
        });
      }

      // 创建导出任务
      const exportTask = await ReportExport.create({
        report_key: reportKey,
        user_id: userId,
        format,
        filters,
        status: 'pending'
      });

      // 异步处理导出任务
      this.processExportTask(exportTask.id, reportKey, filters, format, userId)
        .catch(error => {
          logger.error('处理导出任务失败:', error);
          ReportExport.markFailed(exportTask.id, error.message);
        });

      res.json({
        success: true,
        data: {
          export_id: exportTask.id,
          status: 'pending',
          message: '导出任务已创建，请稍后查看结果'
        }
      });
    } catch (error) {
      logger.error('创建导出任务失败:', error);
      res.status(500).json({
        success: false,
        message: '创建导出任务失败',
        error: error.message
      });
    }
  }

  // 获取导出状态
  async getExportStatus(req, res) {
    try {
      const { exportId } = req.params;
      const userId = req.user?.id;

      const exportTask = await ReportExport.findById(exportId);
      if (!exportTask) {
        return res.status(404).json({
          success: false,
          message: '导出任务不存在'
        });
      }

      // 检查是否为任务创建者
      if (exportTask.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '没有访问此导出任务的权限'
        });
      }

      res.json({
        success: true,
        data: exportTask
      });
    } catch (error) {
      logger.error('获取导出状态失败:', error);
      res.status(500).json({
        success: false,
        message: '获取导出状态失败',
        error: error.message
      });
    }
  }

  // 下载导出文件
  async downloadExport(req, res) {
    try {
      const { exportId } = req.params;
      const userId = req.user?.id;

      const exportTask = await ReportExport.findById(exportId);
      if (!exportTask) {
        return res.status(404).json({
          success: false,
          message: '导出任务不存在'
        });
      }

      // 检查是否为任务创建者
      if (exportTask.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '没有访问此导出任务的权限'
        });
      }

      if (exportTask.status !== 'completed') {
        return res.status(400).json({
          success: false,
          message: '导出任务尚未完成'
        });
      }

      if (exportTask.isExpired()) {
        return res.status(410).json({
          success: false,
          message: '导出文件已过期'
        });
      }

      // 增加下载次数
      await ReportExport.incrementDownloadCount(exportId);

      // 返回下载URL或直接返回文件
      const downloadUrl = exportTask.getDownloadUrl();
      res.json({
        success: true,
        data: {
          download_url: downloadUrl,
          filename: exportTask.filename,
          file_size: exportTask.file_size
        }
      });
    } catch (error) {
      logger.error('下载导出文件失败:', error);
      res.status(500).json({
        success: false,
        message: '下载导出文件失败',
        error: error.message
      });
    }
  }

  // 处理导出任务（异步）
  async processExportTask(exportId, reportKey, filters, format, userId) {
    try {
      // 更新状态为处理中
      await ReportExport.updateStatus(exportId, 'processing');

      // 生成报表数据
      const config = await ReportConfig.findByKey(reportKey);
      let reportData;
      
      switch (config.category) {
        case 'financial':
          reportData = await this.generateFinancialReport(reportKey, filters);
          break;
        case 'sales':
          reportData = await this.generateSalesReport(reportKey, filters);
          break;
        case 'product':
          reportData = await this.generateProductReport(reportKey, filters);
          break;
        case 'customer':
          reportData = await this.generateCustomerReport(reportKey, filters);
          break;
        default:
          throw new Error(`不支持的报表类型: ${config.category}`);
      }

      // 生成文件
      const filename = `${config.name}_${new Date().toISOString().split('T')[0]}.${format}`;
      const filePath = await this.generateExportFile(reportData, format, filename);
      const fileSize = await this.getFileSize(filePath);

      // 标记完成
      await ReportExport.markCompleted(exportId, {
        filename,
        file_path: filePath,
        file_size: fileSize
      });

      logger.info(`导出任务完成: ${exportId}`);
    } catch (error) {
      logger.error(`导出任务失败: ${exportId}`, error);
      await ReportExport.markFailed(exportId, error.message);
    }
  }

  // 生成财务类报表数据（占位符）
  async generateFinancialReport(reportKey, filters) {
    // 这里将在后续实现具体的财务报表逻辑
    return {
      data: [],
      summary: {},
      charts: []
    };
  }

  // 生成销售类报表数据（占位符）
  async generateSalesReport(reportKey, filters) {
    // 这里将在后续实现具体的销售报表逻辑
    return {
      data: [],
      summary: {},
      charts: []
    };
  }

  // 生成商品类报表数据（占位符）
  async generateProductReport(reportKey, filters) {
    // 这里将在后续实现具体的商品报表逻辑
    return {
      data: [],
      summary: {},
      charts: []
    };
  }

  // 生成顾客类报表数据（占位符）
  async generateCustomerReport(reportKey, filters) {
    // 这里将在后续实现具体的顾客报表逻辑
    return {
      data: [],
      summary: {},
      charts: []
    };
  }

  // 生成导出文件（占位符）
  async generateExportFile(data, format, filename) {
    // 这里将实现具体的文件生成逻辑
    return `/exports/${filename}`;
  }

  // 获取文件大小（占位符）
  async getFileSize(filePath) {
    // 这里将实现具体的文件大小获取逻辑
    return 1024;
  }
}

module.exports = new ReportController();